// pages/history/history.js
import * as echarts from '../../ec-canvas/echarts';
import http from "../../utils/http.js"
let chart = null;
var app = getApp()
var ctx = null
var tid = null
// 模拟 cancelAnimationFrame
function abortAnimationFrame(id) {
  clearTimeout(id)
}

// echart init
function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    targetNum: 0,
    drinkNum: 0,
    drinkNumReal: 0,
    remainderNum: 0,
    times: 0,
    progress: 0,
    id: 0,
    ec: {
      onInit: initChart
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.userId
    }) 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getData(this.data.id)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.drawPool()
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },
  drawPool(){
    if(!ctx){
      console.log('draw pool')
      ctx = wx.createCanvasContext('historyPool')
    }
        
    this.wave(ctx, this.data.drinkNum / this.data.targetNum * 100);
  },
  wave (ctx, oRange){
    ctx.clearRect(0, 0, 160, 160);
    var that = this
    var M = Math;
    var Sin = M.sin;
    var Cos = M.cos;
    var Sqrt = M.sqrt;
    var Pow = M.pow;
    var PI = M.PI;
    var Round = M.round;
      // 线宽
    var lineWidth = 2;
    var oW =  160 - lineWidth * 2;
    var oH =  160 - lineWidth * 2;
  
    // 大半径
    var r = (oW / 2);
    var cR = r - lineWidth;
    ctx.beginPath();
    ctx.lineWidth = lineWidth;
    // 水波动画初始参数
    var axisLength = 2 * r;  // Sin 图形长度
    var unit = axisLength / 9; // 波浪宽
    var range = .4 // 浪幅
    var nowrange = range;
    var xoffset = lineWidth  //8 * lineWidth; // x 轴偏移量
    
    var data = ~~(oRange) / 100;   // 数据量
    
    var sp = 0; // 周期偏移量
    var nowdata = 0;
    var waveupsp = 0.006; // 水波上涨速度
    // 圆动画初始参数
    var arcStack = [];  // 圆栈
    var bR = r;
    var soffset = -(PI / 2); // 圆动画起始位置
    var circleLock = true; // 起始动画锁
    // 获取圆动画轨迹点集
    for (var i = soffset; i < soffset + 2 * PI; i += 1 / (8 * PI)) {
      arcStack.push([
        r + bR * Cos(i),
        r + bR * Sin(i)
      ])
    }
    // 圆起始点
    var cStartPoint = arcStack.shift();
    ctx.strokeStyle = "#1c86d1";
    ctx.moveTo(cStartPoint[0], cStartPoint[1]);
    // 开始渲染
    render();
    function drawSine() {
      ctx.beginPath();
      ctx.save();
      var Stack = []; // 记录起始点和终点坐标
      for (var i = xoffset; i <= xoffset + axisLength; i += 20 / axisLength) {
        var x = sp + (xoffset + i) / unit;
        var y = Sin(x) * nowrange;
        var dx = i;
        var dy = 2 * cR * (1 - nowdata) + (r - cR) - (unit * y);
        ctx.lineTo(dx, dy);
        Stack.push([dx, dy])
      }
      // 获取初始点和结束点
      var startP = Stack[0]
      var endP = Stack[Stack.length - 1]
      ctx.lineTo(xoffset + axisLength, oW);
      ctx.lineTo(xoffset, oW);
      ctx.lineTo(startP[0], startP[1])
      ctx.fillStyle = "#62BBFF";
  
      ctx.fill();
      ctx.restore();
    }
    function drawText() {
      ctx.globalCompositeOperation = 'source-over';
      var size = 48 //0.4 * cR;
      ctx.font = 'bold ' + size + 'px DINAlternate-Bold,DINAlternate';
      var number = (nowdata.toFixed(2) * 100).toFixed(0);
      
    
      var txt = (number/100) * that.data.targetNum  //number+ '%';
      var fonty = r + size / 2;
      var fontx = r - size /2;
    
      ctx.fillStyle = '#1A1A1A'
      ctx.textAlign = 'center';
      ctx.fillText(txt, r, r)
      size = 12
  
      txt = "当天总饮水量(毫升)"
      ctx.font =  size + 'px PingFangSC-Regular,PingFang SC';
      fonty = r + size + 10
      fontx = r + size / 2
      ctx.fillText(txt, fontx, fonty)
    }
  
    //最外层淡蓝色圆圈
    function outCircle() {
      ctx.beginPath();
      ctx.lineWidth = 2;
      ctx.strokeStyle = '#C8E7FF';
      ctx.arc(r, r, cR, 0, 2 * Math.PI);
      ctx.stroke();
      ctx.restore();
      ctx.beginPath();
    }
    //橘黄色进度圈
    function orangeCircle() {
      ctx.beginPath();
      ctx.strokeStyle = '#62BBFF';
      //使用这个使圆环两端是圆弧形状
      ctx.lineCap = 'round';
      ctx.arc(r, r, cR - 5, 0 * (Math.PI / 180.0) - (Math.PI / 2), (nowdata * 360) * (Math.PI / 180.0) - (Math.PI / 2));
      ctx.stroke();
      ctx.save()
    }
    //裁剪中间水圈
    function clipCircle() {
      ctx.beginPath();
      ctx.arc(r, r, cR, 0, 2 * Math.PI, false);
      ctx.clip();
    }
    //渲染canvas
    function render() {
      abortAnimationFrame(tid);
  
      ctx.clearRect(0, 0, oW, oH);
      
      //淡蓝色外圈  
      outCircle();
      //最外层进度圈
      //orangeCircle();
      //裁剪中间水圈  
      clipCircle();
      // 控制波幅
      
      if (data >= 0.85) {
        if (nowrange > range / 4) {
          var t = range * 0.01;
          nowrange -= t;
        }
      } else if (data <= 0.1) {
        if (nowrange < range * 1.5) {
          var t = range * 0.01;
          nowrange += t;
        }
      } else {
        if (nowrange <= range) {
          var t = range * 0.01;
          nowrange += t;
        }
        if (nowrange >= range) {
          var t = range * 0.01;
          nowrange -= t;
        }
      }
      if ((data - nowdata) > 0) {
        nowdata += waveupsp;
      }
      if ((data - nowdata) < 0) {
        nowdata -= waveupsp
      }
      sp += 0.07;
      // 开始水波动画
      drawSine();
   
      
      // 写字
      drawText();
  
      ctx.draw();
      
      tid = doAnimationFrame(render);
    }
  
    var lastFrameTime = 0;
    // 模拟 requestAnimationFrame
    function doAnimationFrame(callback) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastFrameTime));
      
      var id = setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
      lastFrameTime = currTime + timeToCall;
      return id;
    };
  },
  getData(id){
    let params = {
      userId: id
    }
    http.request('/drinkRecords/histories',params)
    .then(res=>{
      this.setData({
        times: res.data.info.times,
        drinkNumReal: res.data.info.waterQuantity ? res.data.info.waterQuantity: 0,
        targetNum: res.data.info.waterQuantityPlan,
        remainderNum: res.data.info.waterQuantityBalance
      })
      this.showPool()
      this.setEcharts(res.data.history)
    })
    .catch(res=>{

    })
  },
  showPool(){
    let drinkNumReal = this.data.drinkNumReal // 饮水量
    let drinkNum = 0 // 饮水量变化
    let animationTime = 1500
    let animationTimeReal = animationTime
    let drinkNumInterval = setInterval(() => {
      if (animationTime <= 0) {
        drinkNum = drinkNumReal
        if (drinkNumInterval) {
          clearInterval(drinkNumInterval)
          drinkNumInterval = null
        }
        let progress = parseInt(this.data.drinkNum / this.data.targetNum * 100)
        this.setData({
          drinkNum,
          progress: progress > 100 ? 100 : progress
        })
        return
      }
      drinkNum += parseInt(drinkNumReal * 100 / animationTimeReal)
      let progress = parseInt(this.data.drinkNum / this.data.targetNum * 100)
      this.setData({
        drinkNum,
        progress: progress > 100 ? 100 : progress
      })
      animationTime -= 100

    }, 100)
  },
  setEcharts(data){
    let series = []
    let xData = []
    for(let i = 0; i < data.length; i++){
      let key = Object.keys(data[i])
      xData.push(key)
      series.push(data[i][key])
    }
  
    var option = {
      xAxis: {
        type: 'category',
        boundaryGap: false,
        // show : false,
        axisLine: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisTick: {       //刻度线
          "show": false
        },
        axisLabel: {
          color: "rgba(178, 178, 178, 1)",
          fontSize: 10
        },
        data: xData,
      },
      yAxis: {
        show: false,
        type: 'value',
        splitLine: {
          show: false
        },
        axisTick: {       //y轴刻度线
          "show": false
        },
        axisLabel: {
          show: false
        }
      },
      series: [{
        label: {
          normal: {
            show: true,
            position: 'top'
          }
        },
        data: series,
        type: 'line',
        areaStyle: {
          normal: {
            color: 'rgba(253, 209, 3,0.15)',
          }
        },
        symbol: 'circle',     //折点设定为实心点
        symbolSize: 6,   //设定实心点的大小
        itemStyle: {
          normal: {
            color: 'rgba(253, 209, 3,1)',
            lineStyle: {
              color: 'rgba(253, 209, 3, 1)' //改变折线颜色
            }
          }
        }
      }]
    };
    if (!chart) {
     let interval = setInterval(() => {
        if (chart) {
          chart.setOption(option);
          clearInterval(interval)
          interval = null
        }
      }, 100)
    }
    
    if (chart){
      chart.setOption(option);
    }
  }
})